<template>
  <el-form-item :label="'输入模型属性'">
    <el-tree-select
      v-model="selectedNode"
      filterable
      clearable
      multiple
      :props="{
        label: 'label',
        value: 'path',
      }"
      :data="dataModel"
      @remove-tag="handleRemoveTag"
      placeholder="表单输入模型字段" />
  </el-form-item>
</template>

<script>
import i18n from '@/utils/i18n'
import { get, isArray } from 'lodash-es'
import { EVENT_BUS_KEY } from '@/utils/constants'
import eventBus from '@/utils/event-bus.js'

export default {
  name: 'serviceFieldKey-editor',
  mixins: [i18n],
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object,
  },
  mounted() {
    // console.log('this.optionModel.serviceFieldKey', this.optionModel.serviceFieldKey)
    console.log('this.selectedWidget', this.selectedWidget, this.optionModel)
    eventBus.$on(EVENT_BUS_KEY.CLEAR_ALL_COMPONENT_FROM_TREE, this.clearAll)
  },
  computed: {
    noLabelSetting() {
      return (this.selectedWidget.type === 'static-text') || (this.selectedWidget.type === 'html-text')
      //|| (this.selectedWidget.type === 'divider')
    },
    selectedNode: {
      get() {
        // 遍历所有serviceVersionVOs，找出component数组中包含当前选中组件ID的节点
        const paths = []

        // 使用通用方法遍历树结构
        this.traverseInputModelTree(node => {
          // 检查当前节点是否有component属性且包含当前选中组件ID
          if (node.component && isArray(node.component) && node.component.includes(this.selectedWidget.id)) {
            // 如果找到匹配的节点，添加其path到结果数组
            paths.push(node.path)
          }
        })

        return paths
      },
      set(value) {
        // 添加选中的节点
        value.forEach(key => {
          //根据路径获取到对应服务的输入模型树
          const inputModelTree = this.getInputModelTreeNodeWithKeyPath(key)
          if (inputModelTree) {
            // console.log(111, inputModelTree)
            //  检查当前节点是否有component属性，如果没有，则替换
            const index = inputModelTree.component.indexOf(this.selectedWidget.id)
            if (index === -1) {
              inputModelTree.component.splice(0, 1, this.selectedWidget.id)
            }
          }
        })

        // 清除所有选项时调用，如果没有选中任何节点，则清除所有关联
        if (value.length === 0) {
          // 使用通用方法遍历树结构
          this.traverseInputModelTree(node => {
            // 检查当前节点是否有component属性且包含当前选中组件ID
            if (node.component && isArray(node.component)) {
              const index = node.component.indexOf(this.selectedWidget.id)
              if (index > -1) {
                // 如果找到匹配的节点，从数组中移除
                node.component.splice(index, 1)
              }
            }
          })
        }
      },
    },
    dataModel() {
      //将svvos转换成树型结构，并将path添加到节点的 key 中，只查找有inputModel的服务。
      //因为此处选中组件后需要将组件值与inputModelTree做绑定。
      const dataModel = this.convertServiceVersionToTree(this.designer.formConfig.serviceVersionVOs.filter(item => item.inputModel))
      console.log('dataModel', dataModel)
      return dataModel
    },
  },
  methods: {
    // 通用方法：遍历输入模型树结构并对每个节点执行回调函数
    traverseInputModelTree(callback) {
      this.designer.formConfig.serviceVersionVOs.forEach(serviceVO => {
        if (serviceVO.inputModelTree && serviceVO.inputModelTree.length > 0) {
          // 递归函数用于遍历树结构
          const traverseNode = (node) => {
            // 执行回调函数，传入当前节点
            callback(node)

            // 递归检查子节点
            if (node.children && node.children.length > 0) {
              node.children.forEach(child => traverseNode(child))
            }
          }

          // 从根节点开始递归查找
          serviceVO.inputModelTree.forEach(rootNode => traverseNode(rootNode))
        }
      })
    },

    convertServiceVersionToTree(serviceVersionVOs) {
      return serviceVersionVOs.map(item => {
        return {
          label: item.service.name,
          path: item.service.id, // 服务节点的 path 保持为 service.id
          children: item.inputModelTree?.[0]?.children, // 使用处理过的子节点
        }
      })
    },
    handleRemoveTag(value) {
      // 所以我们应该基于传入的 value (被移除的tag的key) 来操作
      const inputModelTree = this.getInputModelTreeNodeWithKeyPath(value)
      if (inputModelTree) {
        const index = inputModelTree.component.indexOf(this.selectedWidget.id)
        if (index > -1) {
          inputModelTree.component.splice(index, 1)
        }
      }
    },
    clearAll(value) {
      console.log('handleClear - Keys to clear:', value)
      /*if (isArray(value) && value.length === 0) {
        const keysToClear = this.optionModel.serviceFieldKey || []
        console.log('handleClear - Keys to clear:', keysToClear)

        // 使用通用方法遍历树结构，清除所有componentId
        keysToClear.forEach(keyPath => {
          const model = this.getInputModelTreeNodeWithKeyPath(keyPath)
          if (model && model.hasOwnProperty('componentId')) {
            delete model.componentId
            console.log(`Removed componentId from model with key: ${keyPath}`)
          } else {
            console.warn(`Model not found or componentId missing for key: ${keyPath}`)
          }
        })
      }*/
    },

    getInputModelTreeNodeWithKeyPath(pathValue) {
      // 确保 pathValue 是有效的字符串
      if (typeof pathValue !== 'string' || !pathValue) {
        console.error('Invalid path provided to getInputModelTreeNodeWithKeyPath:', pathValue)
        return null
      }
      const parts = pathValue.split('.')
      if (parts.length < 1) {
        console.error('Invalid path format:', pathValue)
        return null
      }
      const serviceId = parts[0]
      const fieldPath = parts.slice(1).join('.') // 重组路径 "[0].children[index]..."
      const serviceVersionVO = this.designer.formConfig.serviceVersionVOs.find(item => item.service.id == serviceId)
      if (serviceVersionVO) {
        try {
          const model = get(serviceVersionVO.inputModelTree, fieldPath)
          if (model === undefined) {
            console.warn(`Model not found at path: ${fieldPath} for serviceId: ${serviceId}`)
            return null
          }
          return model
        } catch (error) {
          console.error(`Error getting model with lodash.get for path: ${fieldPath}`, error)
          return null
        }
      } else {
        console.warn(`ServiceVersionVO not found for serviceId: ${serviceId}`)
        return null
      }
    },
  },
}
</script>

<style lang="scss" scoped>
:deep(.ep-select-group__title) {
  color: black;
  font-weight: bolder;
}
</style>
